import React,{useEffect,useRef,useState} from 'react'
import {DeleteOutlined,EditOutlined}from '@ant-design/icons'
import http from '../../api'
import {Space,Table,Switch,Popconfirm,Modal,Button,message}from 'antd'
import FormDef from '../../components/FormDef'

export default function User() {
  const formRef=useRef(null)
  const [currow,setCurrow]=useState({})
  const [userList,setUserList]=useState([])//用户列表
  const [selectOption,setSelectOption]=useState({
    roleList:[],
    regionList:[]
  })//区域角色下拉
  const [modalInfo, setModalInfo] = useState({
    isModalOpen:false,
    title:'新增',
    isEdit:false,
    disableRegion:false
  });//编辑弹窗显示控制


//编辑打开详情
const getUserDetil=async (record)=>{
  setCurrow(record)
  await setModalInfo({
    isModalOpen:true,
    title:'编辑',
    isEdit:true,
    disableRegion:record.roleId==1
  })
  formRef.current.setFieldsValue({
    ...record,
  })
}

//修改用户状态
const onChange=(record)=>{
  http.patch('/users/'+record.id,{
    roleState:!record.roleState
  }).then(res=>{
    getTableList()
  })
}

//新增用户信息
const handleOk=()=>{
  formRef.current.validateFields().then(res => {
    modalInfo.isEdit? http.post('/users/',{
      ...res,
      "roleState": true,
      "default": false,
    }).then(res=>{
      formRef.current.resetFields()
      setModalInfo({
        title:'新增',
        isEdit:false,
        isModalOpen:false,
        disableRegion:false
      })
      message.success('添加成功')
      getTableList()
    }):
    http.patch('/users/'+currow.id,{
      ...res,
      "roleState": true,
      "default": false,
    }).then(res=>{
      formRef.current.resetFields()
      setModalInfo({
        title:'新增',
        isEdit:false,
        isModalOpen:false,
        disableRegion:false
      })
      message.success('编辑成功')
      getTableList()
    })
  }).catch(err => {
    console.log(err)
  })
}

//取消编辑用户信息
const cancelEdit=()=>{
formRef.current.resetFields()
setModalInfo({
  ...modalInfo,
  isModalOpen:false
})
}

//新增用户
const addUser=()=>{
setModalInfo({
  ...modalInfo,
  isModalOpen:true
})
}

  const column=[
    {
      title: '区域',
      key: 'region',
      render:(_,item)=>(
        <span>{item.region?item.region:'全球'}</span>
      )
    },
    {
      title: '角色名称',
      dataIndex: 'roleName',
      key: 'roleName',
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '用户状态',
      key: 'default',
      render:(_,item)=>(
       <Switch checked={item.roleState} disabled={item.default} onChange={()=>onChange(item)} />
      )
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Popconfirm title="确定要删除么？" okText="确认" cancelText="取消" onConfirm={()=>onConfirmDel(record)}>
          <DeleteOutlined style={{color:'red',marginRight:'10px'}} />
          </Popconfirm>
          <Button type="primary" shape="circle" icon={<EditOutlined />} onClick={()=>getUserDetil(record)}/>
        </Space>
      ),
    },
  ]

  useEffect(()=>{
    getTableList()
    getSelectOptions()
  },[])


  const onConfirmDel=(record)=>{
    const id=record.id
    http.delete('/users/'+id).then(res=>{
      getTableList()
    })
  }


   //获取用户信息
  const getTableList=()=>{
    const getUsers=http.get('/users')
    const getRoles=http.get('/roles')
    Promise.all([getUsers,getRoles]).then(res=>{
      const tableList=res[0].data.map(user=>{
        const roleItem=res[1].data.find(role=>role.id==user.roleId)
        if(roleItem!==-1){
          return {
            ...user,
            roleName:roleItem.roleName
          }
        }else{
          return user
        }
      })
    setUserList(tableList)
    })
  }

  //获取新增编辑下拉信息
  const getSelectOptions=()=>{
    const getRegions=http.get('/regions')
    const getRoles=http.get('/roles')
    Promise.all([getRegions,getRoles]).then(res=>{
      setSelectOption({
        roleList:res[1].data,
        regionList:res[0].data
      })
    })
  }

  return (
    <div>
      <Button onClick={addUser} type='primary'>新增用户</Button>
     <Table columns={column} dataSource={userList} pagination={{ pageSize:5 }} rowKey={(item)=>item.id}/>;
     <Modal title={modalInfo.title} open={modalInfo.isModalOpen} onOk={handleOk} onCancel={cancelEdit}>
     <FormDef selectOption={selectOption} ref={formRef} disableRegion={modalInfo.disableRegion}></FormDef>
      </Modal>
    </div>
  )
}
